<!DOCTYPE html>
<html class="writer-html5" lang="en" data-content_root="../../">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>ib_insync.ibcontroller &mdash; ib_insync 0.9.86 documentation</title>
      <link rel="stylesheet" type="text/css" href="../../_static/pygments.css?v=b76e3c8a" />
      <link rel="stylesheet" type="text/css" href="../../_static/css/theme.css?v=19f00094" />

  
    <link rel="canonical" href="https://ib_insync.readthedocs.io_modules/ib_insync/ibcontroller.html"/>
  <!--[if lt IE 9]>
    <script src="../../_static/js/html5shiv.min.js"></script>
  <![endif]-->
  
        <script src="../../_static/jquery.js?v=5d32c60e"></script>
        <script src="../../_static/_sphinx_javascript_frameworks_compat.js?v=2cd50e6c"></script>
        <script src="../../_static/documentation_options.js?v=b76974d2"></script>
        <script src="../../_static/doctools.js?v=888ff710"></script>
        <script src="../../_static/sphinx_highlight.js?v=dc90522c"></script>
    <script src="../../_static/js/theme.js"></script>
    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" /> 
</head>

<body class="wy-body-for-nav"> 
  <div class="wy-grid-for-nav">
    <nav data-toggle="wy-nav-shift" class="wy-nav-side">
      <div class="wy-side-scroll">
        <div class="wy-side-nav-search" >

          
          
          <a href="../../index.html" class="icon icon-home">
            ib_insync
          </a>
              <div class="version">
                0.9
              </div>
<div role="search">
  <form id="rtd-search-form" class="wy-form" action="../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" aria-label="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>
</div>
        </div><div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="Navigation menu">
              <ul>
<li class="toctree-l1"><a class="reference internal" href="../../readme.html">Introduction</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../api.html">API docs</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../notebooks.html">Notebooks</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../recipes.html">Code recipes</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../code.html">Source code</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../changelog.html">Changelog</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../links.html">Links</a></li>
</ul>

        </div>
      </div>
    </nav>

    <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap"><nav class="wy-nav-top" aria-label="Mobile navigation menu" >
          <i data-toggle="wy-nav-top" class="fa fa-bars"></i>
          <a href="../../index.html">ib_insync</a>
      </nav>

      <div class="wy-nav-content">
        <div class="rst-content">
          <div role="navigation" aria-label="Page navigation">
  <ul class="wy-breadcrumbs">
      <li><a href="../../index.html" class="icon icon-home" aria-label="Home"></a></li>
          <li class="breadcrumb-item"><a href="../index.html">Module code</a></li>
      <li class="breadcrumb-item active">ib_insync.ibcontroller</li>
      <li class="wy-breadcrumbs-aside">
      </li>
  </ul>
  <hr/>
</div>
          <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
           <div itemprop="articleBody">
             
  <h1>Source code for ib_insync.ibcontroller</h1><div class="highlight"><pre>
<span></span><span class="sd">&quot;&quot;&quot;Programmatic control over the TWS/gateway client software.&quot;&quot;&quot;</span>

<span class="kn">import</span> <span class="nn">asyncio</span>
<span class="kn">import</span> <span class="nn">logging</span>
<span class="kn">import</span> <span class="nn">sys</span>
<span class="kn">from</span> <span class="nn">contextlib</span> <span class="kn">import</span> <span class="n">suppress</span>
<span class="kn">from</span> <span class="nn">dataclasses</span> <span class="kn">import</span> <span class="n">dataclass</span>
<span class="kn">from</span> <span class="nn">typing</span> <span class="kn">import</span> <span class="n">ClassVar</span>

<span class="kn">from</span> <span class="nn">eventkit</span> <span class="kn">import</span> <span class="n">Event</span>

<span class="kn">import</span> <span class="nn">ib_insync.util</span> <span class="k">as</span> <span class="nn">util</span>
<span class="kn">from</span> <span class="nn">ib_insync.contract</span> <span class="kn">import</span> <span class="n">Contract</span><span class="p">,</span> <span class="n">Forex</span>
<span class="kn">from</span> <span class="nn">ib_insync.ib</span> <span class="kn">import</span> <span class="n">IB</span>


<div class="viewcode-block" id="IBC">
<a class="viewcode-back" href="../../api.html#ib_insync.ibcontroller.IBC">[docs]</a>
<span class="nd">@dataclass</span>
<span class="k">class</span> <span class="nc">IBC</span><span class="p">:</span>
<span class="w">    </span><span class="sa">r</span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Programmatic control over starting and stopping TWS/Gateway</span>
<span class="sd">    using IBC (https://github.com/IbcAlpha/IBC).</span>

<span class="sd">    Args:</span>
<span class="sd">        twsVersion (int): (required) The major version number for</span>
<span class="sd">            TWS or gateway.</span>
<span class="sd">        gateway (bool):</span>
<span class="sd">            * True = gateway</span>
<span class="sd">            * False = TWS</span>
<span class="sd">        tradingMode (str): &#39;live&#39; or &#39;paper&#39;.</span>
<span class="sd">        userid (str): IB account username. It is recommended to set the real</span>
<span class="sd">            username/password in a secured IBC config file.</span>
<span class="sd">        password (str): IB account password.</span>
<span class="sd">        twsPath (str): Path to the TWS installation folder.</span>
<span class="sd">            Defaults:</span>

<span class="sd">            * Linux:    ~/Jts</span>
<span class="sd">            * OS X:     ~/Applications</span>
<span class="sd">            * Windows:  C:\\Jts</span>
<span class="sd">        twsSettingsPath (str): Path to the TWS settings folder.</span>
<span class="sd">            Defaults:</span>

<span class="sd">            * Linux:     ~/Jts</span>
<span class="sd">            * OS X:      ~/Jts</span>
<span class="sd">            * Windows:   Not available</span>
<span class="sd">        ibcPath (str): Path to the IBC installation folder.</span>
<span class="sd">            Defaults:</span>

<span class="sd">            * Linux:     /opt/ibc</span>
<span class="sd">            * OS X:      /opt/ibc</span>
<span class="sd">            * Windows:   C:\\IBC</span>
<span class="sd">        ibcIni (str): Path to the IBC configuration file.</span>
<span class="sd">            Defaults:</span>

<span class="sd">            * Linux:     ~/ibc/config.ini</span>
<span class="sd">            * OS X:      ~/ibc/config.ini</span>
<span class="sd">            * Windows:   %%HOMEPATH%%\\Documents\IBC\\config.ini</span>
<span class="sd">        javaPath (str): Path to Java executable.</span>
<span class="sd">            Default is to use the Java VM included with TWS/gateway.</span>
<span class="sd">        fixuserid (str): FIX account user id (gateway only).</span>
<span class="sd">        fixpassword (str): FIX account password (gateway only).</span>
<span class="sd">        on2fatimeout (str): What to do if 2-factor authentication times</span>
<span class="sd">            out; Can be &#39;restart&#39; or &#39;exit&#39;.</span>

<span class="sd">    This is not intended to be run in a notebook.</span>

<span class="sd">    To use IBC on Windows, the proactor (or quamash) event loop</span>
<span class="sd">    must have been set:</span>

<span class="sd">    .. code-block:: python</span>

<span class="sd">        import asyncio</span>
<span class="sd">        asyncio.set_event_loop(asyncio.ProactorEventLoop())</span>

<span class="sd">    Example usage:</span>

<span class="sd">    .. code-block:: python</span>

<span class="sd">        ibc = IBC(976, gateway=True, tradingMode=&#39;live&#39;,</span>
<span class="sd">            userid=&#39;edemo&#39;, password=&#39;demouser&#39;)</span>
<span class="sd">        ibc.start()</span>
<span class="sd">        IB.run()</span>
<span class="sd">    &quot;&quot;&quot;</span>

    <span class="n">IbcLogLevel</span><span class="p">:</span> <span class="n">ClassVar</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span>

    <span class="n">twsVersion</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="n">gateway</span><span class="p">:</span> <span class="nb">bool</span> <span class="o">=</span> <span class="kc">False</span>
    <span class="n">tradingMode</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span>
    <span class="n">twsPath</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span>
    <span class="n">twsSettingsPath</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span>
    <span class="n">ibcPath</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span>
    <span class="n">ibcIni</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span>
    <span class="n">javaPath</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span>
    <span class="n">userid</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span>
    <span class="n">password</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span>
    <span class="n">fixuserid</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span>
    <span class="n">fixpassword</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span>
    <span class="n">on2fatimeout</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span>

    <span class="k">def</span> <span class="nf">__post_init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_isWindows</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">platform</span> <span class="o">==</span> <span class="s1">&#39;win32&#39;</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">ibcPath</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">ibcPath</span> <span class="o">=</span> <span class="s1">&#39;/opt/ibc&#39;</span> <span class="k">if</span> <span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">_isWindows</span> <span class="k">else</span> <span class="s1">&#39;C:</span><span class="se">\\</span><span class="s1">IBC&#39;</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_proc</span> <span class="o">=</span> <span class="kc">None</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_monitor</span> <span class="o">=</span> <span class="kc">None</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;ib_insync.IBC&#39;</span><span class="p">)</span>

    <span class="k">def</span> <span class="fm">__enter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
        <span class="k">return</span> <span class="bp">self</span>

    <span class="k">def</span> <span class="fm">__exit__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">_exc</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">terminate</span><span class="p">()</span>

<div class="viewcode-block" id="IBC.start">
<a class="viewcode-back" href="../../api.html#ib_insync.ibcontroller.IBC.start">[docs]</a>
    <span class="k">def</span> <span class="nf">start</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="w">        </span><span class="sd">&quot;&quot;&quot;Launch TWS/IBG.&quot;&quot;&quot;</span>
        <span class="n">util</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">startAsync</span><span class="p">())</span></div>


<div class="viewcode-block" id="IBC.terminate">
<a class="viewcode-back" href="../../api.html#ib_insync.ibcontroller.IBC.terminate">[docs]</a>
    <span class="k">def</span> <span class="nf">terminate</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="w">        </span><span class="sd">&quot;&quot;&quot;Terminate TWS/IBG.&quot;&quot;&quot;</span>
        <span class="n">util</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">terminateAsync</span><span class="p">())</span></div>


<div class="viewcode-block" id="IBC.startAsync">
<a class="viewcode-back" href="../../api.html#ib_insync.ibcontroller.IBC.startAsync">[docs]</a>
    <span class="k">async</span> <span class="k">def</span> <span class="nf">startAsync</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">_proc</span><span class="p">:</span>
            <span class="k">return</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;Starting&#39;</span><span class="p">)</span>

        <span class="c1"># map from field names to cmd arguments; key=(UnixArg, WindowsArg)</span>
        <span class="n">args</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span>
            <span class="n">twsVersion</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="s1">&#39;&#39;</span><span class="p">),</span>
            <span class="n">gateway</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;--gateway&#39;</span><span class="p">,</span> <span class="s1">&#39;/Gateway&#39;</span><span class="p">),</span>
            <span class="n">tradingMode</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;--mode=&#39;</span><span class="p">,</span> <span class="s1">&#39;/Mode:&#39;</span><span class="p">),</span>
            <span class="n">twsPath</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;--tws-path=&#39;</span><span class="p">,</span> <span class="s1">&#39;/TwsPath:&#39;</span><span class="p">),</span>
            <span class="n">twsSettingsPath</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;--tws-settings-path=&#39;</span><span class="p">,</span> <span class="s1">&#39;&#39;</span><span class="p">),</span>
            <span class="n">ibcPath</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;--ibc-path=&#39;</span><span class="p">,</span> <span class="s1">&#39;/IbcPath:&#39;</span><span class="p">),</span>
            <span class="n">ibcIni</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;--ibc-ini=&#39;</span><span class="p">,</span> <span class="s1">&#39;/Config:&#39;</span><span class="p">),</span>
            <span class="n">javaPath</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;--java-path=&#39;</span><span class="p">,</span> <span class="s1">&#39;/JavaPath:&#39;</span><span class="p">),</span>
            <span class="n">userid</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;--user=&#39;</span><span class="p">,</span> <span class="s1">&#39;/User:&#39;</span><span class="p">),</span>
            <span class="n">password</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;--pw=&#39;</span><span class="p">,</span> <span class="s1">&#39;/PW:&#39;</span><span class="p">),</span>
            <span class="n">fixuserid</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;--fix-user=&#39;</span><span class="p">,</span> <span class="s1">&#39;/FIXUser:&#39;</span><span class="p">),</span>
            <span class="n">fixpassword</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;--fix-pw=&#39;</span><span class="p">,</span> <span class="s1">&#39;/FIXPW:&#39;</span><span class="p">),</span>
            <span class="n">on2fatimeout</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;--on2fatimeout=&#39;</span><span class="p">,</span> <span class="s1">&#39;/On2FATimeout:&#39;</span><span class="p">),</span>
        <span class="p">)</span>

        <span class="c1"># create shell command</span>
        <span class="n">cmd</span> <span class="o">=</span> <span class="p">[</span>
            <span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="bp">self</span><span class="o">.</span><span class="n">ibcPath</span><span class="si">}</span><span class="se">\\</span><span class="s1">scripts</span><span class="se">\\</span><span class="s1">StartIBC.bat&#39;</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">_isWindows</span> <span class="k">else</span>
            <span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="bp">self</span><span class="o">.</span><span class="n">ibcPath</span><span class="si">}</span><span class="s1">/scripts/ibcstart.sh&#39;</span><span class="p">]</span>
        <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">util</span><span class="o">.</span><span class="n">dataclassAsDict</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>
            <span class="n">arg</span> <span class="o">=</span> <span class="n">args</span><span class="p">[</span><span class="n">k</span><span class="p">][</span><span class="bp">self</span><span class="o">.</span><span class="n">_isWindows</span><span class="p">]</span>
            <span class="k">if</span> <span class="n">v</span><span class="p">:</span>
                <span class="k">if</span> <span class="n">arg</span><span class="o">.</span><span class="n">endswith</span><span class="p">(</span><span class="s1">&#39;=&#39;</span><span class="p">)</span> <span class="ow">or</span> <span class="n">arg</span><span class="o">.</span><span class="n">endswith</span><span class="p">(</span><span class="s1">&#39;:&#39;</span><span class="p">):</span>
                    <span class="n">cmd</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">arg</span><span class="si">}{</span><span class="n">v</span><span class="si">}</span><span class="s1">&#39;</span><span class="p">)</span>
                <span class="k">elif</span> <span class="n">arg</span><span class="p">:</span>
                    <span class="n">cmd</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">arg</span><span class="p">)</span>
                <span class="k">else</span><span class="p">:</span>
                    <span class="n">cmd</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="n">v</span><span class="p">))</span>

        <span class="c1"># run shell command</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_proc</span> <span class="o">=</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">create_subprocess_exec</span><span class="p">(</span>
            <span class="o">*</span><span class="n">cmd</span><span class="p">,</span> <span class="n">stdout</span><span class="o">=</span><span class="n">asyncio</span><span class="o">.</span><span class="n">subprocess</span><span class="o">.</span><span class="n">PIPE</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_monitor</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">ensure_future</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">monitorAsync</span><span class="p">())</span></div>


<div class="viewcode-block" id="IBC.terminateAsync">
<a class="viewcode-back" href="../../api.html#ib_insync.ibcontroller.IBC.terminateAsync">[docs]</a>
    <span class="k">async</span> <span class="k">def</span> <span class="nf">terminateAsync</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">_proc</span><span class="p">:</span>
            <span class="k">return</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;Terminating&#39;</span><span class="p">)</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">_monitor</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">_monitor</span><span class="o">.</span><span class="n">cancel</span><span class="p">()</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">_monitor</span> <span class="o">=</span> <span class="kc">None</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">_isWindows</span><span class="p">:</span>
            <span class="kn">import</span> <span class="nn">subprocess</span>
            <span class="n">subprocess</span><span class="o">.</span><span class="n">call</span><span class="p">(</span>
                <span class="p">[</span><span class="s1">&#39;taskkill&#39;</span><span class="p">,</span> <span class="s1">&#39;/F&#39;</span><span class="p">,</span> <span class="s1">&#39;/T&#39;</span><span class="p">,</span> <span class="s1">&#39;/PID&#39;</span><span class="p">,</span> <span class="nb">str</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_proc</span><span class="o">.</span><span class="n">pid</span><span class="p">)])</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">with</span> <span class="n">suppress</span><span class="p">(</span><span class="ne">ProcessLookupError</span><span class="p">):</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">_proc</span><span class="o">.</span><span class="n">terminate</span><span class="p">()</span>
                <span class="k">await</span> <span class="bp">self</span><span class="o">.</span><span class="n">_proc</span><span class="o">.</span><span class="n">wait</span><span class="p">()</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_proc</span> <span class="o">=</span> <span class="kc">None</span></div>


<div class="viewcode-block" id="IBC.monitorAsync">
<a class="viewcode-back" href="../../api.html#ib_insync.ibcontroller.IBC.monitorAsync">[docs]</a>
    <span class="k">async</span> <span class="k">def</span> <span class="nf">monitorAsync</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">while</span> <span class="bp">self</span><span class="o">.</span><span class="n">_proc</span><span class="p">:</span>
            <span class="n">line</span> <span class="o">=</span> <span class="k">await</span> <span class="bp">self</span><span class="o">.</span><span class="n">_proc</span><span class="o">.</span><span class="n">stdout</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
            <span class="k">if</span> <span class="ow">not</span> <span class="n">line</span><span class="p">:</span>
                <span class="k">break</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">_logger</span><span class="o">.</span><span class="n">log</span><span class="p">(</span><span class="n">IBC</span><span class="o">.</span><span class="n">IbcLogLevel</span><span class="p">,</span> <span class="n">line</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span><span class="o">.</span><span class="n">decode</span><span class="p">())</span></div>
</div>



<div class="viewcode-block" id="Watchdog">
<a class="viewcode-back" href="../../api.html#ib_insync.ibcontroller.Watchdog">[docs]</a>
<span class="nd">@dataclass</span>
<span class="k">class</span> <span class="nc">Watchdog</span><span class="p">:</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Start, connect and watch over the TWS or gateway app and try to keep it</span>
<span class="sd">    up and running. It is intended to be used in an event-driven</span>
<span class="sd">    application that properly initializes itself upon (re-)connect.</span>

<span class="sd">    It is not intended to be used in a notebook or in imperative-style code.</span>
<span class="sd">    Do not expect Watchdog to magically shield you from reality. Do not use</span>
<span class="sd">    Watchdog unless you understand what it does and doesn&#39;t do.</span>

<span class="sd">    Args:</span>
<span class="sd">        controller (IBC): (required) IBC instance.</span>
<span class="sd">        ib (IB): (required) IB instance to be used. Do not connect this</span>
<span class="sd">            instance as Watchdog takes care of that.</span>
<span class="sd">        host (str): Used for connecting IB instance.</span>
<span class="sd">        port (int):  Used for connecting IB instance.</span>
<span class="sd">        clientId (int):  Used for connecting IB instance.</span>
<span class="sd">        connectTimeout (float):  Used for connecting IB instance.</span>
<span class="sd">        readonly (bool): Used for connecting IB instance.</span>
<span class="sd">        appStartupTime (float): Time (in seconds) that the app is given</span>
<span class="sd">            to start up. Make sure that it is given ample time.</span>
<span class="sd">        appTimeout (float): Timeout (in seconds) for network traffic idle time.</span>
<span class="sd">        retryDelay (float): Time (in seconds) to restart app after a</span>
<span class="sd">            previous failure.</span>
<span class="sd">        probeContract (Contract): Contract to use for historical data</span>
<span class="sd">            probe requests (default is EURUSD).</span>
<span class="sd">        probeTimeout (float); Timeout (in seconds) for the probe request.</span>

<span class="sd">    The idea is to wait until there is no traffic coming from the app for</span>
<span class="sd">    a certain amount of time (the ``appTimeout`` parameter). This triggers</span>
<span class="sd">    a historical request to be placed just to see if the app is still alive</span>
<span class="sd">    and well. If yes, then continue, if no then restart the whole app</span>
<span class="sd">    and reconnect. Restarting will also occur directly on errors 1100 and 100.</span>

<span class="sd">    Example usage:</span>

<span class="sd">    .. code-block:: python</span>

<span class="sd">        def onConnected():</span>
<span class="sd">            print(ib.accountValues())</span>

<span class="sd">        ibc = IBC(974, gateway=True, tradingMode=&#39;paper&#39;)</span>
<span class="sd">        ib = IB()</span>
<span class="sd">        ib.connectedEvent += onConnected</span>
<span class="sd">        watchdog = Watchdog(ibc, ib, port=4002)</span>
<span class="sd">        watchdog.start()</span>
<span class="sd">        ib.run()</span>

<span class="sd">    Events:</span>
<span class="sd">        * ``startingEvent`` (watchdog: :class:`.Watchdog`)</span>
<span class="sd">        * ``startedEvent`` (watchdog: :class:`.Watchdog`)</span>
<span class="sd">        * ``stoppingEvent`` (watchdog: :class:`.Watchdog`)</span>
<span class="sd">        * ``stoppedEvent`` (watchdog: :class:`.Watchdog`)</span>
<span class="sd">        * ``softTimeoutEvent`` (watchdog: :class:`.Watchdog`)</span>
<span class="sd">        * ``hardTimeoutEvent`` (watchdog: :class:`.Watchdog`)</span>
<span class="sd">    &quot;&quot;&quot;</span>

    <span class="n">events</span> <span class="o">=</span> <span class="p">[</span>
        <span class="s1">&#39;startingEvent&#39;</span><span class="p">,</span> <span class="s1">&#39;startedEvent&#39;</span><span class="p">,</span> <span class="s1">&#39;stoppingEvent&#39;</span><span class="p">,</span> <span class="s1">&#39;stoppedEvent&#39;</span><span class="p">,</span>
        <span class="s1">&#39;softTimeoutEvent&#39;</span><span class="p">,</span> <span class="s1">&#39;hardTimeoutEvent&#39;</span><span class="p">]</span>

    <span class="n">controller</span><span class="p">:</span> <span class="n">IBC</span>
    <span class="n">ib</span><span class="p">:</span> <span class="n">IB</span>
    <span class="n">host</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;127.0.0.1&#39;</span>
    <span class="n">port</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">7497</span>
    <span class="n">clientId</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">1</span>
    <span class="n">connectTimeout</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="mi">2</span>
    <span class="n">appStartupTime</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="mi">30</span>
    <span class="n">appTimeout</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="mi">20</span>
    <span class="n">retryDelay</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="mi">2</span>
    <span class="n">readonly</span><span class="p">:</span> <span class="nb">bool</span> <span class="o">=</span> <span class="kc">False</span>
    <span class="n">account</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span>
    <span class="n">raiseSyncErrors</span><span class="p">:</span> <span class="nb">bool</span> <span class="o">=</span> <span class="kc">False</span>
    <span class="n">probeContract</span><span class="p">:</span> <span class="n">Contract</span> <span class="o">=</span> <span class="n">Forex</span><span class="p">(</span><span class="s1">&#39;EURUSD&#39;</span><span class="p">)</span>
    <span class="n">probeTimeout</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="mi">4</span>

    <span class="k">def</span> <span class="nf">__post_init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">startingEvent</span> <span class="o">=</span> <span class="n">Event</span><span class="p">(</span><span class="s1">&#39;startingEvent&#39;</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">startedEvent</span> <span class="o">=</span> <span class="n">Event</span><span class="p">(</span><span class="s1">&#39;startedEvent&#39;</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">stoppingEvent</span> <span class="o">=</span> <span class="n">Event</span><span class="p">(</span><span class="s1">&#39;stoppingEvent&#39;</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">stoppedEvent</span> <span class="o">=</span> <span class="n">Event</span><span class="p">(</span><span class="s1">&#39;stoppedEvent&#39;</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">softTimeoutEvent</span> <span class="o">=</span> <span class="n">Event</span><span class="p">(</span><span class="s1">&#39;softTimeoutEvent&#39;</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">hardTimeoutEvent</span> <span class="o">=</span> <span class="n">Event</span><span class="p">(</span><span class="s1">&#39;hardTimeoutEvent&#39;</span><span class="p">)</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">controller</span><span class="p">:</span>
            <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s1">&#39;No controller supplied&#39;</span><span class="p">)</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">ib</span><span class="p">:</span>
            <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s1">&#39;No IB instance supplied&#39;</span><span class="p">)</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">ib</span><span class="o">.</span><span class="n">isConnected</span><span class="p">():</span>
            <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s1">&#39;IB instance must not be connected&#39;</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_runner</span> <span class="o">=</span> <span class="kc">None</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;ib_insync.Watchdog&#39;</span><span class="p">)</span>

<div class="viewcode-block" id="Watchdog.start">
<a class="viewcode-back" href="../../api.html#ib_insync.ibcontroller.Watchdog.start">[docs]</a>
    <span class="k">def</span> <span class="nf">start</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;Starting&#39;</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">startingEvent</span><span class="o">.</span><span class="n">emit</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_runner</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">ensure_future</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">runAsync</span><span class="p">())</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_runner</span></div>


<div class="viewcode-block" id="Watchdog.stop">
<a class="viewcode-back" href="../../api.html#ib_insync.ibcontroller.Watchdog.stop">[docs]</a>
    <span class="k">def</span> <span class="nf">stop</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;Stopping&#39;</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">stoppingEvent</span><span class="o">.</span><span class="n">emit</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">ib</span><span class="o">.</span><span class="n">disconnect</span><span class="p">()</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_runner</span> <span class="o">=</span> <span class="kc">None</span></div>


<div class="viewcode-block" id="Watchdog.runAsync">
<a class="viewcode-back" href="../../api.html#ib_insync.ibcontroller.Watchdog.runAsync">[docs]</a>
    <span class="k">async</span> <span class="k">def</span> <span class="nf">runAsync</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>

        <span class="k">def</span> <span class="nf">onTimeout</span><span class="p">(</span><span class="n">idlePeriod</span><span class="p">):</span>
            <span class="k">if</span> <span class="ow">not</span> <span class="n">waiter</span><span class="o">.</span><span class="n">done</span><span class="p">():</span>
                <span class="n">waiter</span><span class="o">.</span><span class="n">set_result</span><span class="p">(</span><span class="kc">None</span><span class="p">)</span>

        <span class="k">def</span> <span class="nf">onError</span><span class="p">(</span><span class="n">reqId</span><span class="p">,</span> <span class="n">errorCode</span><span class="p">,</span> <span class="n">errorString</span><span class="p">,</span> <span class="n">contract</span><span class="p">):</span>
            <span class="k">if</span> <span class="n">errorCode</span> <span class="ow">in</span> <span class="p">{</span><span class="mi">100</span><span class="p">,</span> <span class="mi">1100</span><span class="p">}</span> <span class="ow">and</span> <span class="ow">not</span> <span class="n">waiter</span><span class="o">.</span><span class="n">done</span><span class="p">():</span>
                <span class="n">waiter</span><span class="o">.</span><span class="n">set_exception</span><span class="p">(</span><span class="ne">Warning</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;Error </span><span class="si">{</span><span class="n">errorCode</span><span class="si">}</span><span class="s1">&#39;</span><span class="p">))</span>

        <span class="k">def</span> <span class="nf">onDisconnected</span><span class="p">():</span>
            <span class="k">if</span> <span class="ow">not</span> <span class="n">waiter</span><span class="o">.</span><span class="n">done</span><span class="p">():</span>
                <span class="n">waiter</span><span class="o">.</span><span class="n">set_exception</span><span class="p">(</span><span class="ne">Warning</span><span class="p">(</span><span class="s1">&#39;Disconnected&#39;</span><span class="p">))</span>

        <span class="k">while</span> <span class="bp">self</span><span class="o">.</span><span class="n">_runner</span><span class="p">:</span>
            <span class="k">try</span><span class="p">:</span>
                <span class="k">await</span> <span class="bp">self</span><span class="o">.</span><span class="n">controller</span><span class="o">.</span><span class="n">startAsync</span><span class="p">()</span>
                <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">appStartupTime</span><span class="p">)</span>
                <span class="k">await</span> <span class="bp">self</span><span class="o">.</span><span class="n">ib</span><span class="o">.</span><span class="n">connectAsync</span><span class="p">(</span>
                    <span class="bp">self</span><span class="o">.</span><span class="n">host</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">port</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">clientId</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">connectTimeout</span><span class="p">,</span>
                    <span class="bp">self</span><span class="o">.</span><span class="n">readonly</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">account</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">raiseSyncErrors</span><span class="p">)</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">startedEvent</span><span class="o">.</span><span class="n">emit</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">ib</span><span class="o">.</span><span class="n">setTimeout</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">appTimeout</span><span class="p">)</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">ib</span><span class="o">.</span><span class="n">timeoutEvent</span> <span class="o">+=</span> <span class="n">onTimeout</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">ib</span><span class="o">.</span><span class="n">errorEvent</span> <span class="o">+=</span> <span class="n">onError</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">ib</span><span class="o">.</span><span class="n">disconnectedEvent</span> <span class="o">+=</span> <span class="n">onDisconnected</span>

                <span class="k">while</span> <span class="bp">self</span><span class="o">.</span><span class="n">_runner</span><span class="p">:</span>
                    <span class="n">waiter</span><span class="p">:</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">Future</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">Future</span><span class="p">()</span>
                    <span class="k">await</span> <span class="n">waiter</span>
                    <span class="c1"># soft timeout, probe the app with a historical request</span>
                    <span class="bp">self</span><span class="o">.</span><span class="n">_logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;Soft timeout&#39;</span><span class="p">)</span>
                    <span class="bp">self</span><span class="o">.</span><span class="n">softTimeoutEvent</span><span class="o">.</span><span class="n">emit</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
                    <span class="n">probe</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">ib</span><span class="o">.</span><span class="n">reqHistoricalDataAsync</span><span class="p">(</span>
                        <span class="bp">self</span><span class="o">.</span><span class="n">probeContract</span><span class="p">,</span> <span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="s1">&#39;30 S&#39;</span><span class="p">,</span> <span class="s1">&#39;5 secs&#39;</span><span class="p">,</span>
                        <span class="s1">&#39;MIDPOINT&#39;</span><span class="p">,</span> <span class="kc">False</span><span class="p">)</span>
                    <span class="n">bars</span> <span class="o">=</span> <span class="kc">None</span>
                    <span class="k">with</span> <span class="n">suppress</span><span class="p">(</span><span class="n">asyncio</span><span class="o">.</span><span class="n">TimeoutError</span><span class="p">):</span>
                        <span class="n">bars</span> <span class="o">=</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">wait_for</span><span class="p">(</span><span class="n">probe</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">probeTimeout</span><span class="p">)</span>
                    <span class="k">if</span> <span class="ow">not</span> <span class="n">bars</span><span class="p">:</span>
                        <span class="bp">self</span><span class="o">.</span><span class="n">hardTimeoutEvent</span><span class="o">.</span><span class="n">emit</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
                        <span class="k">raise</span> <span class="ne">Warning</span><span class="p">(</span><span class="s1">&#39;Hard timeout&#39;</span><span class="p">)</span>
                    <span class="bp">self</span><span class="o">.</span><span class="n">ib</span><span class="o">.</span><span class="n">setTimeout</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">appTimeout</span><span class="p">)</span>

            <span class="k">except</span> <span class="ne">ConnectionRefusedError</span><span class="p">:</span>
                <span class="k">pass</span>
            <span class="k">except</span> <span class="ne">Warning</span> <span class="k">as</span> <span class="n">w</span><span class="p">:</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">_logger</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="n">w</span><span class="p">)</span>
            <span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">_logger</span><span class="o">.</span><span class="n">exception</span><span class="p">(</span><span class="n">e</span><span class="p">)</span>
            <span class="k">finally</span><span class="p">:</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">ib</span><span class="o">.</span><span class="n">timeoutEvent</span> <span class="o">-=</span> <span class="n">onTimeout</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">ib</span><span class="o">.</span><span class="n">errorEvent</span> <span class="o">-=</span> <span class="n">onError</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">ib</span><span class="o">.</span><span class="n">disconnectedEvent</span> <span class="o">-=</span> <span class="n">onDisconnected</span>
                <span class="k">await</span> <span class="bp">self</span><span class="o">.</span><span class="n">controller</span><span class="o">.</span><span class="n">terminateAsync</span><span class="p">()</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">stoppedEvent</span><span class="o">.</span><span class="n">emit</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
                <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">_runner</span><span class="p">:</span>
                    <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">retryDelay</span><span class="p">)</span></div>
</div>



<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">ibc</span> <span class="o">=</span> <span class="n">IBC</span><span class="p">(</span><span class="mi">1012</span><span class="p">,</span> <span class="n">gateway</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">tradingMode</span><span class="o">=</span><span class="s1">&#39;paper&#39;</span><span class="p">)</span>
    <span class="n">ib</span> <span class="o">=</span> <span class="n">IB</span><span class="p">()</span>
    <span class="n">app</span> <span class="o">=</span> <span class="n">Watchdog</span><span class="p">(</span><span class="n">ibc</span><span class="p">,</span> <span class="n">ib</span><span class="p">,</span> <span class="n">appStartupTime</span><span class="o">=</span><span class="mi">15</span><span class="p">)</span>
    <span class="n">app</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
    <span class="n">IB</span><span class="o">.</span><span class="n">run</span><span class="p">()</span>
</pre></div>

           </div>
          </div>
          <footer>

  <hr/>

  <div role="contentinfo">
    <p>&#169; Copyright 2023, Ewald de Wit.</p>
  </div>

  Built with <a href="https://www.sphinx-doc.org/">Sphinx</a> using a
    <a href="https://github.com/readthedocs/sphinx_rtd_theme">theme</a>
    provided by <a href="https://readthedocs.org">Read the Docs</a>.
   

</footer>
        </div>
      </div>
    </section>
  </div>
  <script>
      jQuery(function () {
          SphinxRtdTheme.Navigation.enable(true);
      });
  </script> 

</body>
</html>